package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    private final StringRedisTemplate stringRedisTemplate ;

    /**
     * 查询商铺类型列表
     *
     * @return
     */
    @Override
    public List<ShopType> queryTypeList() {
        // 1.从缓存中获取数据
        String jsonShopType = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_TYPE_KEY);
        // 2.判断缓存数据是否存在
        if (StrUtil.isNotBlank(jsonShopType)) {
            // 3.存在 直接返回
            log.info("缓存命中");
            List<ShopType> shopTypeList = JSONUtil.toList(jsonShopType, ShopType.class);
            return shopTypeList ;
        }
        log.info("缓存未命中");
        // 4.不存在 根据 id 查询数据库
        List<ShopType> shopTypeList = this.query().orderByAsc("sort").list();
        // 5.判断数据是否存在
        if (shopTypeList == null || shopTypeList.isEmpty()) {
            throw new RuntimeException("店铺类型列表不存在");
        }
        // 6.存在 写入缓存
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_TYPE_KEY, JSONUtil.toJsonStr(shopTypeList), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 7.返回
        return shopTypeList ;
    }
}
